#include "gamewindow.h"
#include <QKeyEvent>
#include <QRandomGenerator>
#include <QGraphicsPixmapItem>
#include <QDebug>
#include <QFile>
#include <QGraphicsTextItem>

// ================= 玩家类实现 =================
void Player::loadPixmapSafe(const QString& path, QPixmap &target) {
    if(QFile::exists(path)) {
        target.load(path);
    }
    if(target.isNull()) {
        qWarning("Failed to load: %s", qUtf8Printable(path));
        target = QPixmap(50, 50);
        target.fill(Qt::red);
    }
}

Player::Player(const QString& normalImg, const QString& jumpImg, QGraphicsItem *parent)
    : QGraphicsPixmapItem(parent)
{
    loadPixmapSafe(normalImg, normalPixmap);
    loadPixmapSafe(jumpImg, jumpingPixmap);

    // 确保至少有一个有效的图像
    if(normalPixmap.isNull() && !jumpingPixmap.isNull()) {
        normalPixmap = jumpingPixmap;
    } else if(!normalPixmap.isNull() && jumpingPixmap.isNull()) {
        jumpingPixmap = normalPixmap;
    }

    normalPixmap = normalPixmap.scaled(50, 50, Qt::KeepAspectRatio, Qt::SmoothTransformation);
    jumpingPixmap = jumpingPixmap.scaled(50, 50, Qt::KeepAspectRatio, Qt::SmoothTransformation);
    setPixmap(normalPixmap);

    isJumping = false;
    velocity = 0;
    jumpCount = 0;
    maxJumpCount = 2;
}

void Player::jump() {
    if (jumpCount < maxJumpCount) {
        velocity = -15;
        isJumping = true;
        jumpCount++;
        setPixmap(jumpingPixmap);
    }
}

void Player::updatePosition() {
    if (isJumping) {
        setPos(x(), y() + velocity);
        velocity += 1.0;
        if (y() >= 250) {
            setPos(x(), 250);
            isJumping = false;
            velocity = 0;
            jumpCount = 0;
            setPixmap(normalPixmap);
        }
    }
}

void Player::resetCharacter() {
    setPixmap(normalPixmap);
    isJumping = false;
    velocity = 0;
    jumpCount = 0;
}

// ================= 游戏窗口类实现 =================
GameWindow::GameWindow(int characterIndex, QWidget *parent)
    : QMainWindow(parent), player(nullptr), score(0), coins(0), isGameOver(false)
{
    // 初始化资源路径
    characterResources = {
        {":/images/resource/images/player.png", ":/images/resource/images/jumpplayer.png"},
        {":/images/resource/images/player2.png", ":/images/resource/images/jumpplayer2.png"}
    };

    // 初始化场景和视图
    scene = new QGraphicsScene(this);
    scene->setSceneRect(0,0,800,400);
    view = new QGraphicsView(scene);
    view->setFixedSize(800,400);
    setCentralWidget(view);
    setFixedSize(800, 400);

    view->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    view->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);

    // 设置背景
    QPixmap bg(":/images/resource/images/background.png");
    if(!bg.isNull()) {
        view->setBackgroundBrush(bg.scaled(800, 400));
    } else {
        view->setBackgroundBrush(Qt::white);
        qDebug() << "Background image not found";
    }

    // 初始化玩家角色
    initializeGame(qBound(0, characterIndex, characterResources.size()-1));

    // 初始化游戏计时器
    timer = new QTimer(this);
    connect(timer, &QTimer::timeout, this, &GameWindow::updateGame);
    timer->start(30);

    // 初始化背景音乐
    bgmOutput = new QAudioOutput(this);
    bgmOutput->setVolume(0.3);
    bgmPlayer = new QMediaPlayer(this);
    bgmPlayer->setAudioOutput(bgmOutput);
    bgmPlayer->setSource(QUrl("qrc:/images/resource/sounds/background.mp3"));
    bgmPlayer->setLoops(QMediaPlayer::Infinite);
    bgmPlayer->play();
}

GameWindow::~GameWindow()
{
    cleanScene();
    delete timer;
    delete bgmPlayer;
    delete bgmOutput;
    delete scene;
    delete view;
}

void GameWindow::initializeGame(int characterIndex)
{
    cleanScene();
    createPlayer(characterIndex);
}

void GameWindow::cleanScene()
{
    if(player) {
        scene->removeItem(player);
        delete player;
        player = nullptr;
    }
}

void GameWindow::createPlayer(int index)
{
    if(index < 0 || index >= characterResources.size()) {
        qWarning("Invalid character index, using default");
        index = 0;
    }

    QString normalPath = characterResources[index].first;
    QString jumpPath = characterResources[index].second;

    // 检查资源是否存在
    if(!QFile::exists(normalPath)) {
        qWarning("Normal image not found: %s", qUtf8Printable(normalPath));
        normalPath = ":/images/resource/images/player.png";
    }
    if(!QFile::exists(jumpPath)) {
        qWarning("Jump image not found: %s", qUtf8Printable(jumpPath));
        jumpPath = ":/images/resource/images/jumpplayer.png";
    }

    player = new Player(normalPath, jumpPath);
    player->setPos(100, 250);
    scene->addItem(player);
}

void GameWindow::keyPressEvent(QKeyEvent *event)
{
    if (isGameOver && event->key() == Qt::Key_R) {
        resetGame();
    } else if (!isGameOver) {
        if (event->key() == Qt::Key_Space || event->key() == Qt::Key_Up) {
            player->jump();
        }
    }
}

void GameWindow::updateGame()
{
    if (!isGameOver) {
        player->updatePosition();
        spawnObstacle();
        spawnCoin();
        checkCollision();
        score++;
        setWindowTitle(QString("游戏 | 得分: %1 | 金币: %2 | 剩余跳跃: %3")
                           .arg(score/10).arg(coins)
                           .arg(player->maxJumpCount - player->jumpCount));
    }
}

void GameWindow::spawnObstacle()
{
    if (QRandomGenerator::global()->bounded(100) < 3) {
        QGraphicsPixmapItem *obstacle = new QGraphicsPixmapItem(
            QPixmap(":/images/resource/images/obstacle.png").scaled(40, 40));
        obstacle->setPos(800, 260);
        obstacle->setData(0, "obstacle");  // 明确标记为障碍物
        scene->addItem(obstacle);
    }

    // 只移动和删除障碍物，不处理金币
    for (auto item : scene->items()) {
        if (item != player && dynamic_cast<QGraphicsPixmapItem*>(item) && item->data(0) == "obstacle") {
            item->setPos(item->x() - 7, item->y());
            if (item->x() < -50) {
                scene->removeItem(item);
                delete item;
            }
        }
    }
}

void GameWindow::spawnCoin()
{
    if (QRandomGenerator::global()->bounded(100) < 3) {
        QGraphicsPixmapItem *coin = new QGraphicsPixmapItem(
            QPixmap(":/images/resource/images/coin.png").scaled(25,25));
        coin->setPos(800, QRandomGenerator::global()->bounded(200) + 50); // 随机高度
        coin->setData(0, "coin");  // 明确标记为金币
        coin->setData(1, QRandomGenerator::global()->bounded(3) + 1); // 金币价值
        scene->addItem(coin);
    }

    // 单独处理金币移动
    for (auto item : scene->items()) {
        if (item != player && dynamic_cast<QGraphicsPixmapItem*>(item) && item->data(0) == "coin") {
            item->setPos(item->x() - 5, item->y()); // 金币移动速度可以比障碍物慢
            if (item->x() < -50) {
                scene->removeItem(item);
                delete item;
            }
        }
    }
}

void GameWindow::checkCollision()
{
    QList<QGraphicsItem*> colliding = player->collidingItems();

    foreach (QGraphicsItem *item, colliding) {
        if (item->data(0) == "coin") {
            coins += item->data(1).toInt(); // 使用存储的金币价值
            score += 50 * item->data(1).toInt();
            scene->removeItem(item);
            delete item;
            // 播放金币收集音效
        }
        else if (item->data(0) == "obstacle") {
            gameOver();
            return;
        }
    }
}

void GameWindow::gameOver()
{
    isGameOver = true;
    timer->stop();
    QGraphicsTextItem *text = scene->addText("游戏结束 按R重新开始", QFont("Arial", 15));
    text->setDefaultTextColor(Qt::blue);
    text->setPos(250, 150);
}

void GameWindow::resetGame()
{
    // 清理所有障碍物和金币
    QList<QGraphicsItem*> itemsToRemove;
    for (auto item : scene->items()) {
        if (item != player && dynamic_cast<QGraphicsPixmapItem*>(item)) {
            itemsToRemove.append(item);
        }
    }

    for (auto item : itemsToRemove) {
        scene->removeItem(item);
        delete item;
    }

    // 重置玩家状态
    if (player) {
        player->resetCharacter();
        player->setPos(100, 250);
    }

    // 重置游戏状态
    score = 0;
    coins = 0;
    isGameOver = false;

    if (!timer->isActive()) {
        timer->start();
    }
}
